<?php
class OutAction extends CommonAction {

    public function index()
    {
        $enter = M('Enter');
        $account = M('Enter_account');
        $enterData = $enter->order('enter_date desc')->where('is_enter_stock=1')->select();

        $allDate = array();

        foreach ($enterData as $k => &$v)
        {
            if (strtotime($v['enter_date']) < time())
                $allDate[] = $v['enter_date'];
        }

        $map['is_enter_stock'] = 1;

        if (isset($_GET['date']))
            $map['enter_date'] = $this->_get('date');

        $data = $enter->field(array('enter_date', 'is_confirm_out'))
                      ->order('enter_date desc')
                      ->where($map)
                      ->limit(1)
                      ->find();

        $currentDate = $data['enter_date'];

        $confirmOut = $data['is_confirm_out'];

        $accountData = $account->where("stuff_date='$currentDate'")->select();

        $outCount = 0;
        foreach($accountData as $k=>$v)
        {
            $outCount += $v['stuff_count'];
        }

        if(isset($_POST['send']))
        {
            $out = M('Out_account');
            $stuffNum = $this->_post('stuff_num');
            $stuffCount = $this->_post('stuff_count');

            foreach ($accountData as $k=>$v)
            {
                $outData['stuff_number'] = $v['stuff_number'];
                $outData['stuff_id'] = $v['stuff_id'];
                $outData['stuff_name'] = $v['stuff_name'];
                $outData['stuff_num'] = $stuffNum[$k];
                $outData['stuff_unit'] = $v['stuff_unit'];
                $outData['stuff_price'] = $v['stuff_price'];
                $outData['stuff_count'] = $stuffCount[$k];
                $outData['stuff_date'] = $v['stuff_date'];

                $out->add($outData);
            }

            $enterData['is_confirm_out'] = 1;
            $enter->where("enter_date='$currentDate'")->save($enterData);

            $this->success('已进入出库台帐，请查看', __URL__.'/index');
        }

        $this->assign(
            array(
                'allDate' => $allDate,
                'accountData' => $accountData,
                'currentDate' => $currentDate,
                'confirmOut' => $confirmOut,
                'outCount' => $outCount,
            )
        );

        $this->display();
    }
}